﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Rpc;
using TouchSocket.Sockets;

namespace Teriri.File.Server.Filter
{
    public class ServiceFilterAttribute : RpcActionFilterAttribute
    {
        /// <summary>
        /// 在执行Rpc之前
        /// </summary>
        public override Task<InvokeResult> ExecutingAsync(ICallContext callContext, object[] parameters, InvokeResult invokeResult)
        {
            if (callContext.Caller is ISocketClient client)
            {
               LoggerHelper.Log<ServiceFilterAttribute>($"即将执行Rpc-{callContext.MethodInstance.Name}");
            }
            return Task.FromResult(invokeResult);
        }

        /// <summary>
        /// 成功执行Rpc后
        /// </summary>
        public override Task<InvokeResult> ExecutedAsync(ICallContext callContext, object[] parameters, InvokeResult invokeResult)
        {
            if (callContext.Caller is ISocketClient client)
            {
                LoggerHelper.Log<ServiceFilterAttribute>($"执行RPC-{callContext.MethodInstance.Name}完成，状态={invokeResult.Status}");
            }

            var newResult = new InvokeResult()
            {
                Status = InvokeStatus.Success,
                Message = "",
                Result = new RpcResultModel()
                {
                    Result = invokeResult.Result,
                    Message = null,
                    Succ = true
                }
            };

            return Task.FromResult(newResult);
        }

        /// <summary>
        /// 执行Rpc遇见异常
        /// </summary>
        public override Task<InvokeResult> ExecutExceptionAsync(ICallContext callContext, object[] parameters, InvokeResult invokeResult, Exception exception)
        {
            if (callContext.Caller is ISocketClient client)
            {
                LoggerHelper.Log<ServiceFilterAttribute>($"执行RPC-{callContext.MethodInstance.Name}异常，信息={invokeResult.Message}");
            }

            var newResult = new InvokeResult()
            {
                Status = InvokeStatus.Success,
                Message = "",
                Result = new RpcResultModel()
                {
                    Result = null,
                    Message = invokeResult.Message,
                    Succ = false
                }
            };

            return Task.FromResult(newResult);
        }
    }
}
